package com.treeroot.userservice.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.treeroot.commonutils.exceptionhandler.MyException;
import com.treeroot.commonutils.utils.JwtUtils;
import com.treeroot.commonutils.utils.MD5;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.treeroot.userservice.user.mapper.AclUserMapper;
import com.treeroot.userservice.user.service.AclUserService;
import com.treeroot.userservice.user.entity.AclUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author TreeRoot
 * @since 2022-06-09
 */
@Service
@Transactional
public class AclUserServiceImpl extends ServiceImpl<AclUserMapper, AclUser> implements AclUserService {

    @Override
    public String login(AclUser aclUser) {
        String username = aclUser.getUsername();
        String password = aclUser.getPassword();
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password)) {
            throw new MyException(20000, "请先填写用户名，密码");
        }
        QueryWrapper<AclUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        AclUser user = baseMapper.selectOne(wrapper);
        if (user == null) {
            throw new MyException(20000, "无此管理员");
        }
        if (!MD5.encrypt(password).equals(user.getPassword())) {

            throw new MyException(20000, "密码错误");
        }

        //生成token字符串，使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(user.getId(), user.getUsername());

        return jwtToken;


    }

    @Override
    public Map getQueryAdminList(long current, long limit, AclUser admin) {
        Page<AclUser> aclUserPage = new Page<>(current,limit);
        //      构建条件
        LambdaQueryWrapper<AclUser> wrapper = new QueryWrapper<AclUser>().lambda()

                .eq(
                        !StringUtils.isEmpty(admin.getName()),
                        AclUser::getName,
                        admin.getName()
                );
        //    调用方法实现查询

        //    调用方法实现查询
        baseMapper.selectPage(aclUserPage, wrapper);
        long total = aclUserPage.getTotal();
        List<AclUser> records = aclUserPage.getRecords();//数据list集合
        Map map =new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return map;
    }
}
